<template>
  <div id="upload" style="background-color: #fff">
    <div
      v-if="district"
      v-html="district"
      class="agreenmsg"
      style="
        width: 100%;
        padding: 5px 10px;
        height: 77%;
        overflow: scroll;
        margin-top: 10px;
      "
    ></div>
    <div style="margin-top: 15px">
      <van-field
        placeholder="请输入姓名"
        :maxlength="10"
        type="text"
        required
        v-model="title"
        v-if="showmes"
      >
        <span slot="label">姓名：</span>
      </van-field>
      <van-field
        placeholder="请输入姓名"
        :maxlength="10"
        type="text"
        v-if="!showmes"
        v-model="title"
        readonly
      >
        <span slot="label">姓名：</span>
      </van-field>
      <van-field
        placeholder="请输入电话"
        :maxlength="11"
        required
        type="number"
        v-model="num"
        v-if="showmes"
      >
        <span slot="label">电话：</span>
      </van-field>
      <van-field
        placeholder="请输入电话"
        :maxlength="11"
        v-if="!showmes"
        type="number"
        v-model="num"
        readonly
      >
        <span slot="label">电话：</span>
      </van-field>
      <van-field
        placeholder="请输入邮箱"
        :maxlength="26"
        required
        v-model="email"
        v-if="showmes"
      >
        <span slot="label">邮箱：</span>
      </van-field>
      <van-field
        placeholder="请输入邮箱"
        :maxlength="26"
        v-if="!showmes"
        v-model="email"
        readonly
      >
        <span slot="label">邮箱：</span>
      </van-field>
      <van-field
        placeholder="请输入身份证号"
        :maxlength="20"
        required
        v-model="idCarder"
        v-if="showmes"
      >
        <span slot="label">身份证号：</span>
      </van-field>
      <van-field
        placeholder="请输入身份证号"
        :maxlength="20"
        v-if="!showmes"
        v-model="idCarder"
        readonly
      >
        <span slot="label">身份证号：</span>
      </van-field>
      <van-field
        placeholder="请输入地址"
        :maxlength="50"
        :show-word-limit="true"
        required
        type="textarea"
        v-if="showmes"
        v-model="adress"
      >
        <span slot="label">地址：</span>
      </van-field>
      <van-field
        placeholder="请输入地址"
        :maxlength="50"
        :show-word-limit="true"
        readonly
        v-if="!showmes"
        type="textarea"
        v-model="adress"
      >
        <span slot="label">地址：</span>
      </van-field>
    </div>
    <p style="width: 90%; margin: 10px auto; padding-top: 10px">
      <b>上传验证信息</b>
    </p>
    <div
      style="display: flex; width: 90%; margin: auto; padding-bottom: 10px"
      v-if="!showmes"
    >
      <img :src="cbf" alt="" width="80px" height="80px" />
      <img
        :src="cfa"
        alt=""
        width="80px"
        height="80px"
        style="margin-left: 8px"
      />
      <img
        :src="cer"
        alt=""
        width="80px"
        height="80px"
        style="margin-left: 8px"
      />
    </div>
    <div style="display: flex; width: 90%; margin: auto" v-if="showmes">
      <van-uploader
        :max-count="1"
        v-model="fileList"
        upload-text="身份证正面"
        style=""
        v-show="show_upload"
        :before-read="beforeRead"
        :after-read="afterRead"
        :before-delete="beforeDelete"
      />

      <van-uploader
        :max-count="1"
        v-model="fileL"
        upload-text="身份证反面"
        style=""
        v-show="show_upload"
        :before-read="beforeReady"
        :after-read="afterReady"
        :before-delete="beforeDeletey"
      />
      <van-uploader
        :max-count="1"
        v-model="fileLs"
        upload-text="营业执照"
        style=""
        v-show="show_upload"
        :before-read="beforeR"
        :after-read="afterR"
        :before-delete="beforeD"
      />
    </div>

    <div style="padding: 0 16px; margin-top: 15px">
      <van-button
        :style="{
          background: !TermsOfService
            ? '#ccc8c8'
            : CardBefore == ''
            ? '#ccc8c8'
            : CardAfter == ''
            ? '#ccc8c8'
            : idCarder == ''
            ? '#ccc8c8'
            : email == ''
            ? '#ccc8c8'
            : adress == ''
            ? '#ccc8c8'
            : '#FF9416',
        }"
        style="width: 100%; color: #fff; font-size: 18px"
        @click="upcard()"
        >确认提交</van-button
      >
    </div>
    <div style="padding: 10px 16px; color: #ee3f00; display: flex">
      <span style="display: inline-block">
        <van-checkbox
          v-model="TermsOfService"
          shape="square"
          checked-color="#07c160"
        ></van-checkbox>
      </span>

      <span
        style="margin-left: 10px"
        :style="{ color: !TermsOfService ? '#ccc8c8' : '#EE3F00' }"
        class="have_read_protocol"
      >
        &ensp;已阅读并同意
        <span @click="showPro">《{{ articleId }}》</span>
      </span>
    </div>

    <!-- 弹窗协议 -->

    <div
      v-show="showprotocol"
      style="
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.3);
        position: fixed;
        overflow: hidden;
        top: 0;
        display: flex;
        flex-flow: column;
        align-items: center;
        padding-bottom: 15%;
      "
    >
      <ul
        style="
          display: flex;
          padding-bottom: 10px;
          flex-flow: column;
          width: 90%;
          height: 90%;
          background: white;
          border-radius: 15px;
          margin: auto;
        "
      >
        <li style="display: flex; width: 100%; height: 9%">
          <div
            style="
              width: 10%;
              padding-left: 22px;
              text-align: center;
              font-size: 25px;
              display: flex;
              align-items: center;
            "
            @click="agreement(1)"
          >
            ×
          </div>
          <div
            style="
              width: 80%;
              padding: 0px 0;
              text-align: center;
              color: #ed3e00;
              font-size: 16px;
              display: flex;
              align-items: center;
            "
          >
            <p style="width: 90%; text-align: center; margin: 0 auto">
              <b>用户协议</b>
            </p>
          </div>
        </li>
        <li
          v-html="district"
          class="addHtml"
          style="width: 100%; height: 90%; overflow: scroll"
        ></li>
        <li style="display: flex; width: 100%; height: 10%">
          <p
            style="
              width: 90%;
              padding: 7px 0;
              text-align: center;
              color: white;
              margin: auto;
              background: #ed3e00;
              font-size: 16px;
              border-radius: 4px;
            "
            @click="agreement(2)"
          >
            <b>我已阅读并了解此条款</b>
          </p>
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
import { Uploader, Toast, Button, Checkbox, Field } from 'vant';
import {
  storageUpload,
  Uploadcard,
  authInfo,
  alliance,
  agreemsg,
  getOrderSign,
} from '@/api/api';
import { setLocalStorage } from '@/utils/local-storage';
import lrz from 'lrz';

export default {
  name: 'upid',
  props: {
    usedId: {
      type: [String, Number],
      default: -1,
    },
  },
  data() {
    return {
      email: '',
      adress: '',
      userLevel: 0,
      showmes: true,
      idCarder: '',
      tel: '',
      is_pinkage: 0,
      is_certificate: 0,
      in_class: -1,
      classoptions: [],
      num: '',
      CardBefore: '',
      CardAfter: '',
      new_level: -1,
      leveloptions: [],
      title: '',
      show: false,
      showprotocol: false,
      price: '',
      src_price: '',
      province_code: '',
      province: '',
      addrCode: '321300',
      city_code: '',
      city: '',
      district_code: '',
      district: '',
      address: '',
      detail: '',
      fileList: [],
      fileL: [],
      fileLs: [],
      license: '',
      show_upload: true,
      TermsOfService: false,
      images: [],
      mobile: '',
      userId: '',
      classId: 'USED.PUBLISH.CLASS',
      newLevelId: 'USED.PUBLISH.NEW.LEVEL',
      fail_reason: '',
      used_userId: '',
      status: -1,
      articleId: '',
      cbf: '',
      cfa: '',
      cer: '',
    };
  },
  mounted() {
    agreemsg({ id: this.$route.query.articleId }).then((res) => {
      this.district = res.data.data.content;
      this.articleId = res.data.data.title;
    });
  },
  created() {
    this.refreshUserInfo();
    alliance({ goodId: Number(this.$route.query.goodId) }).then((res) => {
      if (res.data.data != undefined) {
        this.showmes = false;
        this.title = res.data.data.name;
        this.email = res.data.data.email;
        this.idCarder = res.data.data.idCard;
        this.adress = res.data.data.address;
        this.cbf = res.data.data.idCardBefore;
        this.cfa = res.data.data.idCardAfter;
        this.cer = res.data.data.cer;
        this.CardBefore = this.cbf;
        this.CardAfter = this.cfa;
        this.license = this.cer;
      }
    });
  },
  methods: {
    showPro() {
      this.showprotocol = true;
    },

    agreement(id) {
      this.showprotocol = false;
      if (id == 2) {
        this.TermsOfService = true;
      }
    },
    refreshUserInfo() {
      authInfo().then((res) => {
        this.userId = res.data.data.userId;
        this.mobile = res.data.data.mobile;
        this.num = this.mobile;
        let status = res.data.data.status;
        this.userLevel = res.data.data.userLevel;
        if (status == 0) {
          //未认证
          Toast('请先验证手机号!');
          this.$router.push(`/check`);
        } else {
          //已认证
          setLocalStorage({
            userId: this.userId,
            mobile: this.mobile,
          });
        }
      });
    },

    uploadImg() {
      if (this.fileList.length > 1) return Toast('请上传2张以内的图片');
      this.show_upload = true;
      document.querySelector('.van-uploader__input').click();
      if (this.fileL.length > 1) return Toast('请上传2张以内的图片');
      this.show_upload = true;
      document.querySelector('.van-uploader__input').click();
    },
    beforeRead(file) {
      //上传之前校验
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        Toast('只允许上传jpg/png格式的图片！');
        return false;
      }
      if (file.size >= 5242880) {
        Toast('只允许上传小于5MB的图片！');
        return false;
      }
      return true;
    },
    async afterRead(file) {
      //文件读取完成后的回调函数
      file.status = 'uploading';
      file.message = '上传中...';
      let that = this;
      if (file.size < 1048576) {
        //图片小于1MB不压缩
        //成功时执行
        const formData = new FormData();
        formData.append('file', file.file);
        storageUpload(formData)
          .then((res) => {
            that.images.push(res.data.data.url);
            that.CardBefore = res.data.data.url;
            if (that.CardBefore != undefined) {
              file.status = '';
              file.message = '完成';
            }
          })
          .catch(() => {
            file.status = 'failed';
            file.message = '上传失败';
          });
      } else {
        lrz(file.file, {
          //width : 300
          quality: 0.7, //自定义使用压缩方式
        })
          .then(function (rst) {
            //成功时执行
            storageUpload(rst.formData)
              .then((res) => {
                that.images.push(res.data.data.url);
                that.CardBefore = res.data.data.url;
                if (that.CardBefore != undefined) {
                  file.status = '';
                  file.message = '完成';
                }
              })
              .catch(() => {
                file.status = 'failed';
                file.message = '上传失败';
              });
          })
          .catch(function (error) {
            //失败时执行
            Toast('上传图片尺寸过大');
          })
          .always(function () {
            //不管成功或失败，都会执行
          });
      }
    },
    beforeDelete(file, detail) {
      this.images.splice(detail.index, 1);
      this.CardBefore = '';
      return true;
    },

    // 背面

    beforeReady(file) {
      //上传之前校验
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        Toast('只允许上传jpg/png格式的图片！');
        return false;
      }
      if (file.size >= 5242880) {
        Toast('只允许上传小于5MB的图片！');
        return false;
      }
      return true;
    },
    async afterReady(file) {
      //文件读取完成后的回调函数
      file.status = 'uploading';
      file.message = '上传中...';
      let that = this;
      if (file.size < 1048576) {
        //图片小于1MB不压缩
        //成功时执行
        const formData = new FormData();
        formData.append('file', file.file);
        storageUpload(formData)
          .then((res) => {
            that.images.push(res.data.data.url);
            that.CardAfter = res.data.data.url;
            if (that.CardAfter != undefined) {
              file.status = '';
              file.message = '完成';
            }
          })
          .catch(() => {
            file.status = 'failed';
            file.message = '上传失败';
          });
      } else {
        lrz(file.file, {
          //width : 300
          quality: 0.7, //自定义使用压缩方式
        })
          .then(function (rst) {
            //成功时执行
            storageUpload(rst.formData)
              .then((res) => {
                that.images.push(res.data.data.url);
                that.CardAfter = res.data.data.url;
                if (that.CardAfter != undefined) {
                  file.status = '';
                  file.message = '完成';
                }
              })
              .catch(() => {
                file.status = 'failed';
                file.message = '上传失败';
              });
          })
          .catch(function (error) {
            //失败时执行
            Toast('上传图片尺寸过大');
          })
          .always(function () {
            //不管成功或失败，都会执行
          });
      }
    },
    beforeDeletey(file, detail) {
      this.images.splice(detail.index, 1);
      this.CardAfter = '';

      return true;
    },
    // 营业执照
    beforeR(file) {
      //上传之前校验
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        Toast('只允许上传jpg/png格式的图片！');
        return false;
      }
      if (file.size >= 5242880) {
        Toast('只允许上传小于5MB的图片！');
        return false;
      }
      return true;
    },
    async afterR(file) {
      //文件读取完成后的回调函数
      file.status = 'uploading';
      file.message = '上传中...';
      let that = this;
      if (file.size < 1048576) {
        //图片小于1MB不压缩
        //成功时执行
        const formData = new FormData();
        formData.append('file', file.file);
        storageUpload(formData)
          .then((res) => {
            that.images.push(res.data.data.url);
            that.license = res.data.data.url;
            if (that.license != undefined) {
              file.status = '';
              file.message = '完成';
            }
          })
          .catch(() => {
            file.status = 'failed';
            file.message = '上传失败';
          });
      } else {
        lrz(file.file, {
          //width : 300
          quality: 0.7, //自定义使用压缩方式
        })
          .then(function (rst) {
            //成功时执行
            storageUpload(rst.formData)
              .then((res) => {
                that.images.push(res.data.data.url);
                that.license = res.data.data.url;
                if (that.license != undefined) {
                  file.status = '';
                  file.message = '完成';
                }
              })
              .catch(() => {
                file.status = 'failed';
                file.message = '上传失败';
              });
          })
          .catch(function (error) {
            //失败时执行
            Toast('上传图片尺寸过大');
          })
          .always(function () {
            //不管成功或失败，都会执行
          });
      }
    },
    beforeD(file, detail) {
      this.images.splice(detail.index, 1);
      this.license = '';
      return true;
    },
    //  提交

    upcard() {
      let rightPhone = new RegExp(/^1(3|4|5|6|7|8|9)\d{9}$/);

      if (!this.TermsOfService) {
        Toast('请先阅读协议，并同意！');
        return;
      }
      let txt =
        /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
      if (!txt.test(this.idCarder)) {
        Toast('请输入正确的身份证号');
        return;
      }
      if (this.CardBefore == '') {
        Toast('请上传身份证正面');
        return;
      }
      if (this.CardAfter == '') {
        Toast('请上传身份证反面');
        return;
      }
      if (this.email == '') {
        Toast('请输邮箱');
        return;
      }
      if (!rightPhone.test(this.num)) {
        Toast('请输入正确的号码');
        return;
      }
      if (this.adress == '') {
        Toast('请输入地址');
        return;
      }
      Uploadcard({
        positionId: this.$route.query.positionId,
        idCard: String(this.idCarder),
        idCardAfter: this.CardAfter,
        idCardBefore: this.CardBefore,
        email: this.email,
        cer: this.images[0],
        address: this.adress,
        goodId: this.$route.query.goodId,
        articleId: this.$route.query.articleId,
      })
        .then((res) => {
          Toast('提交成功！');
          this.pay(1, res);
        })
        .catch((err) => {
          Toast(err.data.errmsg);
        });
    },
    pay(type, res) {
      if (typeof WeixinJSBridge == 'undefined') {
        if (document.addEventListener) {
          document.addEventListener(
            'WeixinJSBridgeReady',
            onBridgeReady1,
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', onBridgeReady1);
          document.attachEvent('onWeixinJSBridgeReady', onBridgeReady1);
        }
      } else {
        let that = this;
        console.log(that);
        const setbank = JSON.parse(res.data.data.info.wcPayData);
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest',
          {
            appId: setbank.appId, //公众号名称，由商户传入
            timeStamp: setbank.timeStamp, //时间戳，自1970年以来的秒数
            nonceStr: setbank.nonceStr, //随机串
            package: setbank.package,
            signType: setbank.signType, //微信签名方式：
            paySign: setbank.paySign, //微信签名
          },
          function (res) {
            if (res.err_msg == 'get_brand_wcpay_request:ok') {
              that.$router.push({
                name: 'paymentStatus',
              });
            }
          }
        );
      }
    },
    onBridgeReady1() {
      getOrderSign({
        orderId: this.$route.query.goodId,
      }).then((res) => {
        let that = this;

        that.orderSn = res.data.data.orderSn;

        const Mfbank = JSON.parse(res.data.data.info.wcPayData);

        WeixinJSBridge.invoke(
          'getBrandWCPayRequest',
          {
            appId: Mfbank.appId, //公众号名称，由商户传入
            timeStamp: Mfbank.timeStamp, //时间戳，自1970年以来的秒数
            nonceStr: Mfbank.nonceStr, //随机串
            package: Mfbank.package,
            signType: Mfbank.signType, //微信签名方式：
            paySign: Mfbank.paySign, //微信签名
          },
          function (res) {
            if (res.err_msg == 'get_brand_wcpay_request:ok') {
              //跳转到开通会员接口
              setTenCardOnline({
                orderSn: that.orderSn,
                goodId: this.vipid,
              }).then((res) => {
                let status = 0;
                if (res.data.errmsg == '成功') {
                  status = 1;
                }
                that.$router.push({
                  name: 'paymentVipStatus',
                  query: {
                    status: status,
                  },
                });
              });
            }
          }
        );
      });
    },
  },

  components: {
    [Checkbox.name]: Checkbox,
    [Field.name]: Field,
    [Uploader.name]: Uploader,
    [Toast.name]: Toast,
    [Button.name]: Button,
  },
};
</script>
<style lang="scss" scoped>
/deep/.van-uploader__upload {
  background: #e6e6e6a8 !important;
}
/deep/.van-uploader {
  display: block;
}
.agreenmsg {
  /deep/ p {
    width: 100%;
    img {
      width: 100%;
      height: auto;
    }
  }
}
.addHtml {
  padding: 0 11px;
  /deep/ p {
    margin: 0;
    width: 100%;
    img {
      width: 100%;
      height: auto;
    }
  }
}
</style>
